package com.example.xinlijiankangsys.service;

import com.example.xinlijiankangsys.mapper.CommentMapper;
import com.example.xinlijiankangsys.mapper.PostMapper;
import com.example.xinlijiankangsys.pojo.Comment;
import com.example.xinlijiankangsys.pojo.Post;
import com.example.xinlijiankangsys.pojo.PageResult;
import com.example.xinlijiankangsys.pojo.PostWithComments;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class PostService {

    @Autowired
    private PostMapper postMapper;
    @Autowired
    private CommentMapper commentMapper;

    public Post createPost(Post post) {
        postMapper.insert(post);
        return postMapper.selectById(post.getPostId());
    }

    /**
     * 根据postId获取帖子及其评论
     * @param postId 帖子ID
     * @return 包含帖子和评论的对象
     */
    public PostWithComments getPostWithComments(Long postId) {
        // 1. 查询帖子基本信息
        Post post = postMapper.selectById(postId);
        if (post == null) {
            return null;
        }

        // 2. 查询该帖子的所有评论
        List<Comment> comments = commentMapper.selectByPostId(postId);

        // 3. 组装返回对象
        PostWithComments postWithComments = new PostWithComments();
        postWithComments.setPost(post);
        postWithComments.setComments(comments);

        return postWithComments;
    }

    public PageResult<Post> getPostsByPage(int page, int pageSize) {
        // 参数校验
        if (page < 1) page = 1;
        if (pageSize > 100 || pageSize < 1) pageSize = 10;

        // 计算分页
        int offset = (page - 1) * pageSize;
        List<Post> posts = postMapper.selectByPage(offset, pageSize);
        int total = postMapper.selectTotalCount();
        int totalPages = (int) Math.ceil((double) total / pageSize);

        return new PageResult<>(posts, total, page, pageSize, totalPages);
    }

    public void likePost(Long postId) {
        postMapper.incrementLikeCount(postId);
    }

    public void deletePost(Long postId) {
        postMapper.deleteById(postId);
    }
}